<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import MapConfirmDialog from './MapConfirmDialog.vue'

const loading = ref(false)
const todayAttendance = ref(null)
let refreshTimer = null

// 控制自动刷新的标志
let isUserOperating = false

const buttonDisabled = ref(false)

// 获取今日考勤记录
const fetchTodayAttendance = async () => {
  try {
    loading.value = true
    const today = new Date().toISOString().split('T')[0]
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime()
    
    // 使用更明确的URL参数
    const url = `/attendances/my?startDate=${today}&endDate=${today}&_t=${timestamp}`
    
    const response = await axios.get(url, {
      headers: {
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache'
      }
    })
    
    if (response.data && Array.isArray(response.data) && response.data.length > 0) {
      const attendance = response.data[0]
      // 深拷贝对象，避免引用问题
      todayAttendance.value = JSON.parse(JSON.stringify(attendance))
    } else {
      // 设置空记录而不是null
      todayAttendance.value = {
        id: null,
        checkInTime: null,
        checkOutTime: null,
        status: null,
        date: new Date().toISOString().split('T')[0]
      }
    }
  } catch (error) {
    console.error('获取今日考勤记录失败:', error)
    
    // 设置空记录而不是null
    todayAttendance.value = {
      id: null,
      checkInTime: null,
      checkOutTime: null,
      status: null,
      date: new Date().toISOString().split('T')[0]
    }
  } finally {
    loading.value = false
  }
}

// 确保考勤状态字段存在
const ensureAttendanceFields = (attendance) => {
  if (!attendance) return null
  
  // 创建深拷贝
  const result = JSON.parse(JSON.stringify(attendance))
  
  // 确保关键字段存在
  if (!result.date) {
    result.date = new Date().toISOString().split('T')[0]
  }
  
  return result
}

const mapDialogVisible = ref(false)
const tempLocation = ref({ latitude: 0, longitude: 0 })
const mapDialogVisibleForOut = ref(false)
const tempLocationForOut = ref({ latitude: 0, longitude: 0 })

// 签到
const clockIn = async () => {
  if (buttonDisabled.value) return;
  buttonDisabled.value = true;
  try {
    isUserOperating = true
    loading.value = true
    // 1. 获取地理位置
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        tempLocation.value = {
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude
        }
        mapDialogVisible.value = true
        loading.value = false
      },
      (err) => {
        ElMessage.error('获取定位失败')
        loading.value = false
        buttonDisabled.value = false
      }
    )
  } catch (error) {
    loading.value = false
    buttonDisabled.value = false
  }
}

const onMapConfirm = async ({ latitude, longitude, address }) => {
  try {
    loading.value = true
    const response = await axios.post('/attendances/clock-in-with-location', {
      latitude, longitude, address, locationSource: 'GPS'
    })
    if (response.data && response.data.id) {
      todayAttendance.value = ensureAttendanceFields(response.data)
      ElMessage.success('签到成功')
    } else {
      ElMessage.warning('签到数据异常，请手动刷新页面')
    }
  } catch (error) {
    ElMessage.error('签到失败，请重试')
  } finally {
    loading.value = false
    buttonDisabled.value = false
  }
}

// 签退相关
const clockOut = async () => {
  if (buttonDisabled.value) return;
  buttonDisabled.value = true;
  try {
    isUserOperating = true
    loading.value = true
    navigator.geolocation.getCurrentPosition(
      (pos) => {
        tempLocationForOut.value = {
          latitude: pos.coords.latitude,
          longitude: pos.coords.longitude
        }
        mapDialogVisibleForOut.value = true
        loading.value = false
      },
      (err) => {
        ElMessage.error('获取定位失败')
        loading.value = false
        buttonDisabled.value = false
      }
    )
  } catch (error) {
    loading.value = false
    buttonDisabled.value = false
  }
}

const onMapConfirmForOut = async ({ latitude, longitude, address }) => {
  try {
    loading.value = true
    const response = await axios.post('/attendances/clock-out-with-location', {
      latitude, longitude, address, locationSource: 'GPS'
    })
    if (response.data && response.data.id) {
      todayAttendance.value = ensureAttendanceFields(response.data)
      ElMessage.success('签退成功')
    } else {
      ElMessage.warning('签退数据异常，请手动刷新页面')
    }
  } catch (error) {
    ElMessage.error('签退失败，请重试')
  } finally {
    loading.value = false
    buttonDisabled.value = false
  }
}

// 格式化考勤状态
const formatStatus = (status) => {
  if (!status) return '未知'
  
  const statusMap = {
    'NORMAL': '正常',
    'LATE': '迟到',
    'EARLY_LEAVE': '早退',
    'ABSENT': '缺勤',
    'LEAVE': '请假'
  }
  
  return statusMap[status] || status
}

// 获取状态标签类型
const getStatusType = (status) => {
  if (!status) return ''
  
  const typeMap = {
    'NORMAL': 'success',
    'LATE': 'warning',
    'EARLY_LEAVE': 'warning',
    'ABSENT': 'danger',
    'LEAVE': 'info'
  }
  
  return typeMap[status] || ''
}

// 格式化时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '未记录'
  try {
    const date = new Date(dateTime)
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    // yyyy/M/d HH:mm:ss
    const y = date.getFullYear()
    const m = date.getMonth() + 1
    const d = date.getDate()
    const hh = String(date.getHours()).padStart(2, '0')
    const mm = String(date.getMinutes()).padStart(2, '0')
    const ss = String(date.getSeconds()).padStart(2, '0')
    return `${y}/${m}/${d} ${hh}:${mm}:${ss}`
  } catch (error) {
    return String(dateTime)
  }
}

// 添加定时刷新功能 - 改为空函数，不执行自动刷新
const startAutoRefresh = () => {
  // 不启用自动刷新
}

// 确保组件卸载时清除定时器（虽然现在没有使用，但保留逻辑以便将来可能恢复）
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
})

// 修改onMounted函数
onMounted(async () => {
  await fetchTodayAttendance()
})

const onMapCancel = () => {
  mapDialogVisible.value = false;
  loading.value = false;
  buttonDisabled.value = false;
};
const onMapCancelForOut = () => {
  mapDialogVisibleForOut.value = false;
  loading.value = false;
  buttonDisabled.value = false;
};
</script>

<template>
  <div class="clock-container">
    <el-card shadow="hover" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>今日打卡</h3>
          <div class="date">{{ new Date().toLocaleDateString() }}</div>
        </div>
      </template>
      
      <div class="clock-status">
        <div class="status-item">
          <div class="status-label">签到状态</div>
          <div class="status-value">
            <el-tag v-if="todayAttendance && todayAttendance.checkInTime" type="success">
              已签到: {{ formatDateTime(todayAttendance.checkInTime) }}
            </el-tag>
            <el-tag v-else type="info">未签到</el-tag>
          </div>
        </div>
        
        <div class="status-item">
          <div class="status-label">签退状态</div>
          <div class="status-value">
            <el-tag v-if="todayAttendance && todayAttendance.checkOutTime" type="success">
              已签退: {{ formatDateTime(todayAttendance.checkOutTime) }}
            </el-tag>
            <el-tag v-else type="info">未签退</el-tag>
          </div>
        </div>
        
        <div class="status-item" v-if="todayAttendance && todayAttendance.status">
          <div class="status-label">考勤状态</div>
          <div class="status-value">
            <el-tag :type="getStatusType(todayAttendance.status)">
              {{ formatStatus(todayAttendance.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="status-item" v-if="todayAttendance && todayAttendance.remark">
          <div class="status-label">备注</div>
          <div class="status-value remark-text">
            {{ todayAttendance.remark }}
          </div>
        </div>
      </div>
      
      <div class="clock-actions">
        <MapConfirmDialog
          v-model="mapDialogVisible"
          :latitude="tempLocation.latitude"
          :longitude="tempLocation.longitude"
          map-id="map-in"
          @confirm="onMapConfirm"
          @cancel="onMapCancel"
        />
        <MapConfirmDialog
          v-model="mapDialogVisibleForOut"
          :latitude="tempLocationForOut.latitude"
          :longitude="tempLocationForOut.longitude"
          map-id="map-out"
          @confirm="onMapConfirmForOut"
          @cancel="onMapCancelForOut"
        />
        <el-button 
          type="primary" 
          @click="clockIn"
          :loading="loading"
          :disabled="loading || buttonDisabled || (todayAttendance && !!todayAttendance.checkInTime)"
        >
          <el-icon><Timer /></el-icon>签到
        </el-button>
        
        <el-button 
          type="success" 
          :disabled="!todayAttendance || loading || buttonDisabled || (todayAttendance && !!todayAttendance.checkOutTime)"
          @click="clockOut"
          :loading="loading"
        >
          <el-icon><Position /></el-icon>签退
        </el-button>
        
        <el-button
          type="info"
          @click="async () => { 
            isUserOperating = true; 
            ElMessage.info('正在手动刷新考勤数据...');
            await fetchTodayAttendance(); 
            ElMessage.success('考勤数据刷新成功');
            isUserOperating = false;
          }"
          :loading="loading"
          :disabled="loading"
        >
          <el-icon><Refresh /></el-icon>手动刷新
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.clock-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.date {
  font-size: 14px;
  color: #909399;
}

.clock-status {
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.status-label {
  font-weight: bold;
}

.remark-text {
  font-size: 12px;
  color: #606266;
  word-break: break-all;
  max-width: 70%;
}

.clock-actions {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 